/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bio;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Random;
import helper.BagWithNumbers;
import helper.Config;

/**
 *
 * @author Andrzej
 */
public class Chromosome implements Cloneable{

    public int length(){
        return dna.length;
    }

    private Random random = Config.getSalt();

    private BitSet[] dna;
    private int lengthOfGene;

    public Chromosome(int numberOfSensors, int lengthOfGene) {
        dna = new BitSet[numberOfSensors];
        this.lengthOfGene = lengthOfGene;

    }
   public void setAllele(int index, BitSet value){
        dna[index]  = value;
    }
        public BitSet  getAllele(int index){
       return dna[index];
    }

    public void mutatate() {
        int point = random.nextInt(dna.length);
        int c = dna[point].cardinality();
        BitSet mutated = randomGen(c);
        while (mutated.equals(dna[point]))
            mutated = randomGen(c);
        dna[point] = mutated;

    }

    private BitSet randomGen(int numberOfOnes){
        BitSet bs = new BitSet(lengthOfGene);
        BagWithNumbers bwn = new BagWithNumbers(lengthOfGene);
        for (int i= 0; i <numberOfOnes; i++){
            bs.set(bwn.drawNumber());
        }
        return bs;
    }



    public List<Chromosome> singlePointCrossover(Chromosome parent2){

         int point = 1 + random.nextInt(dna.length -1);
        Chromosome child1 = this;
        Chromosome child2 = parent2;

        for (int i=point; i < dna.length; i++){
                child1.setAllele(i, parent2.getAllele(i));
                child2.setAllele(i, getAllele(i));
        }
        List<Chromosome> children = new ArrayList(2);
        children.add(child1);
        children.add(child2);
        return children;
    }

    @Override
    protected Chromosome clone(){
        Chromosome clone = new Chromosome(dna.length, lengthOfGene);
        for (int i=0; i< dna.length; i++){
            clone.setAllele(i, (BitSet) this.getAllele(i).clone());
        }
        return clone;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        if (dna[0] == null)
            return "error converting to string";
        for (int i=0; i < lengthOfGene;i++){
            for (int j=0; j< dna.length; j++){
                sb.append(dna[j].get(i) ? "1 " : "0 ");
            }
        }
        return sb.toString();
    }





}
